package server

import (
	"errors"
	"math/rand"
	"watermelon/common/models/mysql"
	"watermelon/common/models/redis"
	user "watermelon/common/proto"
)

func SendSms(in *user.SendSmsReq) (*user.SendSmsResp, error) {
	code := rand.Intn(9000) + 1000
	redis.SetRedis("SendSms"+in.Source+in.Mobile, code)

	return &user.SendSmsResp{Greet: "发送成功"}, nil

}

func UserLogin(in *user.UserLoginReq) (*user.UserLoginResp, error) {
	val := redis.GetRedis("SendSms" + "login" + in.Mobile).Val()
	if val != in.Code {
		return nil, errors.New("验证码错误")
	}
	if val == "" {
		return nil, errors.New("验证码已失效")
	}
	u := &mysql.User{}
	mobile, err := u.FindUserByMobile(in.Mobile)
	if err != nil {
		return nil, errors.New("查询失败")
	}
	if mobile.ID == 0 {
		createUser, err := u.CreateUser(in)
		if err != nil {
			return nil, errors.New("注册失败")
		}
		mobile = createUser
	}
	return &user.UserLoginResp{Greet: int64(mobile.ID)}, nil
}

func UserItem(in *user.UserItemReq) (*user.UserItemResp, error) {
	u := &mysql.User{}
	id, err := u.FindUserById(in.UserId)
	if err != nil {
		return nil, errors.New("查询失败")
	}
	return &user.UserItemResp{
		Url:      id.Url,
		Username: id.Username,
	}, nil
}
func ForgetPassword(in *user.ForgetPasswordReq) (*user.ForgetPasswordResp, error) {
	u := &mysql.User{}
	err := u.UpdatePassword(in.UserId, in.Password)
	if err != nil {
		return nil, errors.New("修改失败")
	}
	return &user.ForgetPasswordResp{Greet: "修改成功"}, nil
}
func UserCar(in *user.UserCarReq) (*user.UserCarResp, error) {
	t := &mysql.Trip{}
	err := t.CreateTrip(in)
	if err != nil {
		return nil, errors.New("创建失败")
	}
	return &user.UserCarResp{Greet: "创建成功"}, nil
}
